/*!
 * TidyBlog 2.0
 * Comment - v1.0.0 (2013-10-07T10:22:00+0800)
 * https://code.google.com/p/tidyblog/ | Released under MIT license
 */
define(function(require, exports, module) { 'use strict';

var $ = require('dom/1.0.x/'),
	ajax = require('ajax/1.1.x/'),
	tmpl = require('tmpl/1.0.x/'),
	widget = require('widget/1.0.x/'),
	Paginator = require('paginator/1.0.x/'),
	Validator = require('validator/1.0.x/'),
	Captcha = require('/common/captcha/1.0.x/'),
	util = require('/common/util/1.0.x/');


var templates = {
	LIST:
'<% for (var i = 0; i < data.length; i++) { %>' +
'<article<% if (data[i].AuthorId > 0) { %> class="comment-by-blogger"<% } %>>' +
	'<header>' +
		'<address class="comment-author">' +
	'<% if (data[i].HomePage) { %>' +
		'<a href="<%=data[i].HomePage%>" target="_blank"><%=data[i].AuthorName%></a>' +
   '<% } else { %>' +
		'<%=data[i].AuthorName%>' +
	'<% } %></address> 在 <time><%=data[i].PostTime%></time> 说：' +
	'</header>' +
	'<div class="comment-content"><%=data[i].Content%></div>' +
'</article><% } %>' +
'<div class="paginator-wrapper"></div>',
	TIPS: '<p class="comment-tips"><%=tips%></p>'
};


return widget.create(function(options) {
	
}, {
	_init: function(options) {
		var t = this;
		// 评论表单
		t._form = options.form;
		// 评论列表容器
		t._listWrapper = options.listWrapper;
		// 文章编号
		t._articleId = t._form.find('input[name=ArticleId]').val();

		if (t._form && t._form.length) {
			t._textboxFocus = function() {
				$(this).parent().addClass('textbox-with-label-focus');
				$(this).next('label').css('display', 'none');
			};
			t._textboxBlur = function() {
				$(this).parent().removeClass('textbox-with-label-focus');
				$(this).next('label').css('display', this.value.trim() ? 'none' : 'block');
			};
			var textboxes = t._form.find('.textbox-with-label .form-text')
				.focus(t._textboxFocus).blur(t._textboxBlur).blur();

			// 重置表单后，文本框都被清空，触发一次blur显示label
			t._formReset = function() {
				setTimeout(function() {
					textboxes.blur();
				}, 10);
			};
			t._form.on('reset', t._formReset);

			t._captcha = new Captcha({
				wrapper: t._form.find('.captcha-img')
			});

			// 表单验证
			var minCommentLen = parseInt( $("#comment-minlength").val() ),
				maxCommentLen = parseInt( $("#comment-maxlength").val() );
			var steps = [{
				fields: 'Content',
				message: '评论内容不能少于' + minCommentLen + '个字',
				rule: function(val) { return val.length >= minCommentLen; }
			}, {
				fields: 'Content',
				message: '评论内容不能多于' + maxCommentLen + '个字',
				rule: function(val) { return val.length <= maxCommentLen; }
			}];
			if (!t._form.find('p.comment-user').length) {
				// 未登录的时候需要填写称呼、验证码，Email选填
				steps.push(
					{
						fields: 'Email',
						rule: 'isEmail',
						message: 'Email格式错误',
						required: false
					},
					{ fields: 'AuthorName', message: '请填写您的称呼' },
					{ fields: 'captcha',  message: '请填写验证码' }
				);
			}
			t._validator = new Validator({
				form: t._form,
				steps: steps,
				events: {
					submiterror: util.onSubmitError,
					beforesubmit: function(e) {
						var btn = $(e.target).find('input[type=submit]');
						if ( btn.attr('disabled') ) {
							alert('正在提交评论，请稍后');
							e.preventDefault();
						} else {
							btn.val('发表中，请稍后').attr('disabled', true);
						}
					}
				},
				submitProxy: function(data, form) {
					ajax.send({
						url: form.attr('action'),
						method: 'POST',
						dataType: 'json',
						data: data,
						onsuccess: function(result) {
							if (result.Message) { alert(result.Message); }
							if (result.CommentData) {
								t._render(result.CommentData, true);
							}
							t._captcha.refresh();
						},
						oncomplete: function() {
							form.trigger('reset');
							form.find('input[type=submit]')
								.val('发 表').attr('disabled', false);
						}
					});
				}
			});
		} else {
			delete t._form;
		}

		t.load(1);
	},

	_destroy: function() {
		var t = this;
		if (t._form) {
			t._form.off('reset', t._formReset)
				.find('.textbox-with-label .form-text')
				.off('focus', t._textboxFocus)
				.off('blur', t._textboxBlur);
			delete t._textboxFocus;
			delete t._textboxBlur;
			delete t._formReset;
			delete t._form;

			t._captcha.destroy();
			delete t._captcha;

			t._validator.destroy();
			delete t._validator;
		}

		delete t._form;
		delete t._listWrapper;
		delete t._articleId;
		if (t._paginator) {
			t._paginator.destroy();
			delete t._paginator;
		}
	},

	load: function(page, isResetPosition) {
		var t = this;
		if (t._paginator) {
			t._paginator.destroy();
			delete t._paginator;
		}
		t._listWrapper.html(
			tmpl.render(templates.TIPS, {
				tips : "正在加载评论，请稍候..."
			})
		);

		ajax.send({
			url: '/Comment/List',
			dataType: "json",
			data: {
				articleId : t._articleId,
				page : page
			},
			onsuccess : function(result) { t._render(result, isResetPosition); }
		});
	},

	_render: function(result, isResetPosition) {
		var t = this;
		if (result.Data && result.Data.length) {
			result.Data.forEach(function(d) {
				d.PostTime = util.iFormatDate( util.parseCSharpDate(d.PostTime) );
				d.Content = util.htmlEncode(d.Content).replace(/\r\n/g, '<br />');
			});

			t._listWrapper.html(
				tmpl.render(templates.LIST, {
					data : result.Data
				})
			);

			if (result.PageCount > 1) {
				t._paginator = new Paginator({
					wrapper: t._listWrapper.find('div.paginator-wrapper'),
					currentPage: result.CurrentPage,
					totalPages: result.PageCount,
					events: {
						click: function(e) {
							t.load(e.page, true);
						}
					}
				});
			}
		} else {
			t._listWrapper.html(
				tmpl.render(templates.TIPS, {
					tips : "暂无评论"
				})
			);
		}

		if (isResetPosition) { window.location.hash = 'comment-list'; }
	}
})

});